package com.mall.order.biz.handler;

import com.mall.commons.tool.exception.BizException;
import com.mall.commons.tool.utils.NumberUtils;
import com.mall.order.biz.callback.SendEmailCallback;
import com.mall.order.biz.callback.TransCallback;
import com.mall.order.biz.context.CreateOrderContext;
import com.mall.order.biz.context.TransHandlerContext;
import com.mall.order.constant.OrderRetCode;
import com.mall.order.constants.OrderConstants;
import com.mall.order.dal.entitys.Order;
import com.mall.order.dal.entitys.OrderItem;
import com.mall.order.dal.persistence.OrderItemMapper;
import com.mall.order.dal.persistence.OrderMapper;
import com.mall.order.dto.CartProductDto;
import com.mall.order.utils.GlobalIdGeneratorUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.naming.ldap.PagedResultsControl;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 *  ciggar
 * create-date: 2019/8/1-下午5:01
 * 初始化订单 生成订单
 */

@Slf4j
@Component
public class InitOrderHandler extends AbstractTransHandler {

    private static final String ORDER_ID = "ORDER_ID";

    private static final String ORDER_ITEM_ID = "ORDER_ITEM_ID";

    private static final String ORDER_UNIQUE_KEY = "ORDER_UNIQUE_KEY";

    @Autowired
    GlobalIdGeneratorUtil globalIdGeneratorUtil;

    @Autowired
    OrderMapper orderMapper;

    @Autowired
    OrderItemMapper orderItemMapper;


    @Override
    public boolean isAsync() {
        return false;
    }

    @Override
    public boolean handle(TransHandlerContext context) {
        try {
            // 订单插入数据库
            Order order = new Order();
            CreateOrderContext orderContext = (CreateOrderContext) context;
            order.setUserId(orderContext.getUserId());
            order.setBuyerNick(orderContext.getBuyerNickName());
            order.setPayment(orderContext.getOrderTotal());
            order.setStatus(OrderConstants.ORDER_STATUS_INIT);
            order.setCreateTime(new Date());
            order.setUpdateTime(new Date());
            // 生成订单id
            String orderId = globalIdGeneratorUtil.getNextSeq(ORDER_ID, 1);
            // 生成订单unique_key
            String uniqueKey = globalIdGeneratorUtil.getNextSeq(ORDER_UNIQUE_KEY, 1);
            order.setOrderId(orderId);
            order.setUniqueKey(uniqueKey);
            orderContext.setOrderId(orderId);
            orderContext.setUniqueKey(uniqueKey);
            orderMapper.insert(order);
            // 订单商品信息插入数据库
            for (CartProductDto productDto : orderContext.getCartProductDtoList()) {
                OrderItem item = new OrderItem();
                String itemId = globalIdGeneratorUtil.getNextSeq(ORDER_ITEM_ID, 1);
                item.setId(itemId);
                item.setItemId(productDto.getProductId());
                item.setOrderId(orderId);
                item.setNum(productDto.getProductNum().intValue());
                item.setTitle(productDto.getProductName());
                item.setPrice(NumberUtils.toDouble(productDto.getSalePrice()));
                item.setTotalFee(productDto.getSalePrice()
                        .multiply(BigDecimal.valueOf(productDto.getProductNum())).doubleValue());
                item.setPicPath(productDto.getProductImg());
                item.setStatus(1);
                item.setCreateTime(new Date());
                item.setUpdateTime(new Date());
                orderItemMapper.insert(item);
            }
        } catch (Exception e) {
            log.error("InitOrderHandler occur Exception :" + e);
            throw new BizException(OrderRetCode.DB_SAVE_EXCEPTION.getCode(),
                    OrderRetCode.DB_SAVE_EXCEPTION.getMessage());
        }
        return true;
    }
}
